#include "qmissionmanager.h"

#include "qmission.h"

QMissionManager::QMissionManager(QObject *parent) :
    QObject(parent)
{
}

QMissionManager::~QMissionManager()
{
    qDeleteAll(m_missions);
    m_missions.clear();
    m_id_to_mission.clear();
}

void QMissionManager::set_max_read(int read)
{
    m_max_read=read;
}

void QMissionManager::set_max_write(int write)
{
    m_max_write=write;
}

QString QMissionManager::add_mission(tagDriverDataInfo *info)
{
    QString ret;
    foreach(QMission* ms,m_missions)
    {
        ret=ms->add_address_inforamtion(info);
        if(ret!="")
        {
            return ret;
        }
    }

    QMission *ms=new QMission;
    ret=ms->add_address_inforamtion(info);
    if(ret=="")
    {
        delete ms;
    }
    else
    {
        m_id_to_mission.insert(ms->get_uuid(),ms);
        m_missions.append(ms);
    }
    return ret;
}

void QMissionManager::remove_mission(const QString &uuid)
{
    foreach(QMission* ms,m_missions)
    {
        if(ms->remove_address_information(uuid))
        {
            if(ms->get_address_info().size()==0)
            {
                m_id_to_mission.remove(ms->get_uuid());
                m_missions.removeAll(ms);
                delete ms;
            }
            return;
        }
    }
}

void QMissionManager::delete_mission(const QString &uuid)
{
    QMission* ms=m_id_to_mission.value(uuid);
    if(ms!=NULL)
    {
        m_id_to_mission.remove(uuid);
        m_missions.removeAll(ms);
        delete ms;
    }
}

QMission* QMissionManager::get_need_todo()
{
    double d=0;
    double dd;
    QMission *s=NULL;
    foreach(QMission* ms,m_missions)
    {
        if(ms->get_mission_status()==MS_RETRY)
        {
            return ms;
        }
        dd=ms->get_todo();
        if(dd==0)
        {
            continue;
        }
        if(d<dd)
        {
            if(s==NULL)
            {
                s=ms;
                d=dd;
            }
            else
            {
                if(s->get_level()>=ms->get_level())
                {
                    s=ms;
                    d=dd;
                }
            }
        }
        else if(d==dd)
        {
            if(s->get_level()>ms->get_level())
            {
                s=ms;
                d=dd;
            }
        }
    }

    return s;
}

void QMissionManager::update_send()
{

}

QMission* QMissionManager::get_mission(const QString &id)
{
    return m_id_to_mission.value(id);
}

QList<QMission*> QMissionManager::get_missions()
{
    return m_missions;
}

void QMissionManager::clear()
{
    qDeleteAll(m_missions);
    m_missions.clear();
}
